package cn.yili12.business.service;

import cn.yili12.business.cache.FriendCache;
import cn.yili12.business.entity.CountBean;
import cn.yili12.business.entity.FriendDb;
import cn.yili12.business.entity.MessageDb;
import cn.yili12.business.entity.UserDb;
import cn.yili12.business.repository.FriendRepository;
import cn.yili12.business.repository.MessageRepository;
import cn.yili12.business.repository.UserRepository;
import cn.yili12.common.util.IdTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserService {
    @Autowired
    private UserRepository repository;
    @Autowired
    private IdTool idTool;
    @Autowired
    private FriendRepository friendRepository;
    @Autowired
    private FriendCache friendCache;
    @Autowired
    private MessageRepository messageRepository;

    @Cacheable(value = "user", key = "#phone")
    public UserDb getByPhone(String phone) {
        return repository.getByPhone(phone);
    }

    @Cacheable(value = "user", key = "#id")
    public UserDb getById(Long id) {
        Optional<UserDb> byId = repository.findById(id);
        return byId.get();
    }


    public UserDb save(UserDb userDb) {
        userDb.setId(idTool.createId());
        return repository.save(userDb);
    }

    public List<UserDb> findByOrgId(Long orgId) {
        return repository.findByOrgId(orgId);
    }


    private Map<String, MessageDb> getLastMsgMap(Long userId) {
        List<MessageDb> lastMessage = messageRepository.findLastMessage(String.valueOf(userId));
        Map<String, MessageDb> map = new HashMap<>();
        for (MessageDb messageDb : lastMessage) {
            map.put(messageDb.getFromUser(), messageDb);
        }
        return map;
    }

    private Map<String, Integer> getUnReadMap(Long userId) {
        List<CountBean> unRead = messageRepository.findUnRead(String.valueOf(userId));
        Map<String, Integer> map = new HashMap<>();
        for (CountBean bean : unRead) {
            map.put(bean.getName(), Integer.valueOf(bean.getCount().toString()));
        }
        return map;
    }


    public List<UserDb> findFriend(Long userId) {
        List<UserDb> friendByUser = repository.findFriendByUser(userId);
        // 封装最新消息和时间
        Map<String, MessageDb> lastMsgMap = getLastMsgMap(userId);
        Map<String, Integer> unReadMap = getUnReadMap(userId);
        friendByUser.forEach(item -> {
            MessageDb messageDb = lastMsgMap.get(String.valueOf(item.getId()));
            if (messageDb != null) {
                item.setLastMsg(messageDb.getData());
                item.setUpdateTime(messageDb.getSendTime());
            }
            Integer unread = unReadMap.get(String.valueOf(item.getId()));
            item.setUnread(unread == null ? 0 : unread);
        });
        //按照更新时间排序
        friendByUser.sort((o1, o2) -> {
            return o1.getUpdateTime().before(o2.getUpdateTime()) ? 1 : -1;
        });
        return friendByUser;
    }


    public FriendDb saveOrUpdateFriend(Long userId, Long friendId) {
        FriendDb friendDb = friendRepository.getByUserIdAndFriendId(userId, friendId);
        if (null == friendDb) {
            friendDb = new FriendDb();
            friendDb.setAddTime(new Date());
            friendDb.setFriendId(friendId);
            friendDb.setUserId(userId);
            friendDb.setId(idTool.createId());
        }
        friendDb.setUpdateTime(new Date());
        friendRepository.save(friendDb);
        friendCache.add(String.valueOf(userId), String.valueOf(friendId));
        return friendDb;
    }


}
